<template>
  <div>    
    <Header :title="t('cmp.page_design')"/>
    <el-card class="card">
      <div class="button-group" style="gap: 12px;">
        <el-button text @click="() => settingsDialogVisible = true">
          <svg-icon icon-class="OutlinedSetting" style="font-size: 24px" />
        </el-button>
        <el-button type="primary" @click="doSave" v-loading.fullscreen.lock="fullscreenLoading">
          {{ t('common.save') }} </el-button>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane name="membership" :label="t('modules.pass.membership_card')">
          <div style="min-height: 500px;">
            <div class="menu">
              <button class="menu-item" :class="{active: store.activeMenu === 'AddItem'}" @click="() => store.setActiveMenu('AddItem')">
                <span class="menu-icon">
                  <svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="PlaylistPlusIcon" style="width: 1em; height: 1em; font-size: 28px;"><path d="M3 16H10V14H3M18 14V10H16V14H12V16H16V20H18V16H22V14M14 6H3V8H14M14 10H3V12H14V10Z"></path></svg>
                </span>
                <span class="menu-title">{{ t('flypass.add-item') }}</span>
              </button>

              <button class="menu-item" :class="{active: store.activeMenu === 'Theme'}" @click="() => store.setActiveMenu('Theme')">
                <span class="menu-icon">
                  <svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="PaletteIcon"  style="width: 1em; height: 1em; font-size: 28px;"><path d="M17.5,12A1.5,1.5 0 0,1 16,10.5A1.5,1.5 0 0,1 17.5,9A1.5,1.5 0 0,1 19,10.5A1.5,1.5 0 0,1 17.5,12M14.5,8A1.5,1.5 0 0,1 13,6.5A1.5,1.5 0 0,1 14.5,5A1.5,1.5 0 0,1 16,6.5A1.5,1.5 0 0,1 14.5,8M9.5,8A1.5,1.5 0 0,1 8,6.5A1.5,1.5 0 0,1 9.5,5A1.5,1.5 0 0,1 11,6.5A1.5,1.5 0 0,1 9.5,8M6.5,12A1.5,1.5 0 0,1 5,10.5A1.5,1.5 0 0,1 6.5,9A1.5,1.5 0 0,1 8,10.5A1.5,1.5 0 0,1 6.5,12M12,3A9,9 0 0,0 3,12A9,9 0 0,0 12,21A1.5,1.5 0 0,0 13.5,19.5C13.5,19.11 13.35,18.76 13.11,18.5C12.88,18.23 12.73,17.88 12.73,17.5A1.5,1.5 0 0,1 14.23,16H16A5,5 0 0,0 21,11C21,6.58 16.97,3 12,3Z"></path></svg>
                </span>
                <span class="menu-title">{{t('flypass.theme')}}</span>
              </button>

              <button class="menu-item" :class="{active: store.activeMenu === 'QRCode'}" @click="() => store.setActiveMenu('QRCode')">
                <span class="menu-icon">
                  <svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="QrcodeIcon" style="width: 1em; height: 1em; font-size: 28px;"><path d="M3,11H5V13H3V11M11,5H13V9H11V5M9,11H13V15H11V13H9V11M15,11H17V13H19V11H21V13H19V15H21V19H19V21H17V19H13V21H11V17H15V15H17V13H15V11M19,19V15H17V19H19M15,3H21V9H15V3M17,5V7H19V5H17M3,3H9V9H3V3M5,5V7H7V5H5M3,15H9V21H3V15M5,17V19H7V17H5Z"></path></svg>
                </span>
                <span class="menu-title">{{ t('flypass.qr-code') }}</span>
              </button>

              <button class="menu-item" :class="{active: store.activeMenu === 'Location'}" @click="() => store.setActiveMenu('Location')">
                <span class="menu-icon">
                  <svg-icon icon-class="MapLocation" style="font-size: 28px;"></svg-icon>
                </span>
                <span class="menu-title">{{ t('modules.tms.group.location') }}</span>
              </button>

              <button class="menu-item" :class="{active: store.activeMenu === 'BlueTooth'}" @click="() => store.setActiveMenu('BlueTooth')">
                <span class="menu-icon">
                  <svg t="1638788456705" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7415" width="28" height="28">
                    <path fill="currentColor" d="M538.608 744.992l139.36-88.416-139.136-107.68-0.224 196.096z m139.328-372.32l-138.816-101.44-0.208 195.04 139.024-93.6zM291.488 336.96l9.952-12.496a16 16 0 0 1 22.304-2.688l166.784 129.088 0.272-242.88a16 16 0 0 1 25.44-12.88l226.72 165.744a16 16 0 0 1-0.48 26.192l-178.848 120.4 179.68 139.056a16 16 0 0 1-1.216 26.16l-227.36 144.256a16 16 0 0 1-24.592-13.52l0.272-246.656-167.36 112.672a16 16 0 0 1-22.08-4.16l-9.072-13.104a16 16 0 0 1 4.224-22.384l185.664-125.008-187.584-145.168a16 16 0 0 1-2.72-22.624z" p-id="7416"></path>
                  </svg>
                </span>
                <span class="menu-title">{{ t('flypass.beacon') }}</span>
              </button>

            
            </div>
            <div class="content">
              <component :is="componentMap[store.activeMenu]" />              
              <Center />
              <Right />
            </div>
          </div>

        
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <Settings v-model:visible="settingsDialogVisible" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import AddItem from './add-item.vue'
import QrCode from './qrcode.vue'
import Theme from './theme.vue'
import Location from './location.vue'
import Bluetooth from './blueTooth.vue'
import Center from './center.vue'
import Right from './right.vue'
import { getTemplateInfo, saveTemplate, updateTemplate } from '@/api/pass/template'
import Settings from './settings.vue'
import { usePassStore } from '@/store/modules/pass'
import { ElMessage } from '@toms/element-ui'
import { useI18n } from 'vue-i18n'
import html2canvas from 'html2canvas'
import { uploadFile } from '@/api/file'
import type { Field } from '#/pass'
import { mapImage } from '@/views/pass-center/design/barCodeImage'
import Header from '../components/header.vue'

const activeTab = ref('membership')
const settingsDialogVisible = ref(false)
const fullscreenLoading = ref(false)

const { t } = useI18n()
const store = usePassStore()
const { params } = useRoute()
const baseUrl = import.meta.env.VITE_APP_PROXY

const componentMap = {
  AddItem: AddItem,
  QRCode: QrCode,
  Theme: Theme,
  Location: Location,
  BlueTooth: Bluetooth
}

onMounted(async () => {
  await localGetTemplateInfo()
})

async function localImageToUuid(path: string) {
  const res = await fetch(path)
  const blob = await res.blob()
  const formData = new FormData()
  formData.append('file', blob)
  const { fileUuid } = await uploadFile(formData)
  return fileUuid
}


async function localGetTemplateInfo() {
  if(params.id === 'new') {
    const stripUuid = await localImageToUuid('./assets/铂金.png')
    store.setStripUuid(stripUuid)
    const logoUuid = await localImageToUuid('./assets/unionpay.png')
    store.setLogoUuid(logoUuid)
    store.setIconUuid(logoUuid)
    return
  }
  fullscreenLoading.value = true
  const templateInfo = await getTemplateInfo(params.id as string)
  fullscreenLoading.value = false
  store.setStripImage(baseUrl + '/tempres' + templateInfo.stripUrl)
  store.setHeadLogo(baseUrl +  '/tempres'+  templateInfo.logoUrl)  
  const backFields:Field[] =  templateInfo.backFields.map(field => ({...field, id: field.key, position: 'Detail'}))
  const headFields:Field[] = templateInfo.headerFields.map(field => ({...field, id: field.key, position: 'Head'}))
  const primaryFields:Field[] = templateInfo.secondaryFields.map(field => ({...field, id: field.key, position: 'Body'}))
  const newItems = [...backFields, ...headFields, ...primaryFields]
  store.setItems(newItems)
  if(templateInfo.barcodes.length === 0) {
    store.setShowBarcode(false)
  }
  for(let item of newItems) {
    store.removeFieldsItem(item.key)
  }
  store.setPassTemplateFromInfo(templateInfo)
  if(templateInfo.barcodes.length > 0) {
    store.setBarCodeImage(mapImage[templateInfo.barcodes[0].format])  
  }
}

function generateThumb():Promise<string> {
  return new Promise(async (resolve, reject) => {
    const el = document.getElementById('PassCard')
   
    if(el) {
      el.classList.add('saving') 
      const canvas = await html2canvas(el, {
        useCORS: true
      })
      canvas.toBlob(async function(blob) {
        if(blob) {
          const formData = new FormData();
          formData.append('file', blob);
          const {fileUuid} = await uploadFile(formData)
          el.classList.remove('saving')
          resolve(fileUuid)     
        }
      });
    }
  })
}

async function doSave() {   
  
  
  if(!store.passTemplate.passTypeIdentifier) {
    ElMessage({
      type: 'error',
      message: t('flypass.pass-type-identifier-is-null-please-check-it')
    })
    return
  }
  fullscreenLoading.value = true
  
  const thumbUuid = await generateThumb()
  store.setThumbUuid(thumbUuid)
  
  store.setPassTemplateField('secondaryFields', store.items.filter(item　=> item.position === 'Body'))
  store.setPassTemplateField('headerFields', store.items.filter(item　=> item.position === 'Head'))
  store.setPassTemplateField('backFields', store.items.filter(item　=> item.position === 'Detail'))  
  try {    
    if(params.id === 'new') {
      await saveTemplate(store.passTemplate)
    } else {
      await updateTemplate(params.id as string, store.passTemplate)
    }
    ElMessage({
      type: 'success',
      message: t('common.message.operation_success')
    })
    fullscreenLoading.value = false
  } catch(e) {    
    fullscreenLoading.value = false
    ElMessage({
      type: 'error',
      message: e.message
    })
  }
  
}

onBeforeUnmount(() => {
  store.$reset()
})


</script>

<style lang="scss" scoped>
@import './styles/index.scss';

:deep(.el-tabs__header) {
  margin: 0;
  padding: 20px 20px 0 5px;
}

:deep(.el-tabs__content) {
  // overflow: visible;
}

:deep(.el-card){
  --el-card-padding: 0;
}


.button-group {
  @apply flex items-center;  
  right: 20px;
  z-index: 2;
  position: absolute;
  top: 20px;
}

.card {
  position: relative;
  margin: -150px 20px 0 20px;
  // transform: translateY(-150px);
}

.menu {
  width: 100%;
  display: flex;  
  z-index: 5;
  border-bottom: 1px solid rgb(229, 229, 229);    
  .menu-title {
    font-size: 12px;
  }
  .menu-item {
    width: 100px;
    cursor: pointer;
    height: 69px;
    display: flex;
    padding: 8px;
    min-width: 64px;
    text-align: center;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    &.active {
      color: var(--color-geekblue-8);
      background-color: var(--color-geekblue-1);
    }
    .menu-icon svg {
      fill: currentcolor;
    }

  }
}

.content {
  width: 100%;
  display: flex;
  flex-flow: wrap;

}
</style>